<?php

namespace app\admin\controller;

use app\admin\controller\Utils\FileImport;
use app\app\model\ProjectModel;
use app\app\model\ProjectRiskModel;
use app\BaseController;
use app\Request;
use PhpOffice\PhpSpreadsheet\Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Filesystem;


class ProjectRisk extends BaseController
{
    public function list()
    {
        $data = $this->request->param();
        $page_size = input('pageSize', '20');
        $where = "1=1";
        if (!empty($data['oper_time'])) {
            $where .= "  AND a.oper_time = " . $data['oper_time'];
        }
        if (!empty($data['risk_level'])) {
            $where .= " AND a.risk_level = " . $data['risk_level'];
        }
        if (isset($data['user_name']) && !empty($data['user_name'])) {
            $where .= " AND b.link_user_id like '%" . $data['user_name'] . "%'";
        }

        $list = ProjectRiskModel::alias('a')->field('a.*')
            ->leftjoin('t_project b', 'b.id = a.project_id')
            ->where($where)->paginate([
                'list_rows' => $page_size,
                'var_page' => 'pageNum',
            ]);
        $this->success('success', $list);
    }

    public function add(Request $request)
    {
        $data = $request->param();
        $model = new ProjectRiskModel();
        $data['oper_time'] = date('Y-m-d H:i:s', time());
        $result = $model->save($data);
        if ($result !== false) {
            $this->success('添加成功!');
        } else {
            $this->error("保存失败！");
        }
    }

    public function update(Request $request)
    {
        $data = $request->param();
        $id = $request->param('id', 0, 'intval');
        $result = ProjectRiskModel::strict(false)->where('id', $id)->update($data);
        if ($result !== false) {
            $this->success("保存成功！");
        } else {
            $this->error("保存失败！");
        }
    }


    public function delete(Request $request)
    {
        $data = $request->param();
        $ids = $data['ids'];
        ProjectRiskModel::destroy(function ($query) use ($ids) {
            $query->where('id', 'in', $ids);
        });
    }

    /**
     * 风险等级导入
     * @return void
     * @throws Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Kongkai
     * @date 2022-03-11
     */
    public function importData()
    {
        // 获取表单上传文件
        if (empty(request()->file('file'))) {
            $this->error("请上传文件！");
        }

        try {
            $file = request()->file();
        } catch (\Exception $e) {
            $this->error("文件上传失败");
        }

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:52428800|fileExt:xls,xlsx'])
                ->check($file);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

        $file_path = root_path('runtime') . 'storage/';
        $file_name = Filesystem::putFile(date('Ymd') . '/' . 'risk', $file['file']);

        $data = (new FileImport())->ExcelImport($file_path . $file_name);

        $insert_array = [];
        $error_array = [];
        $i = 0;

        foreach ($data as $k => $v) {
            $i++;

            if ($k == 0) continue;

            $project = ProjectModel::where('project_name', $v[1])->find();
            if (empty($project)) {
                $error_array[] = '第' . $i .  '行项目名称异常';
                continue;
            }

            $project_id = $project->id;

            $insert_array[] = [
                'project_no' => $v[0] ?: null,
                'project_id' => $project_id,
                'project_name' => $v[1] ?: null,
                'work_type' => $v[2] ?: null,
                'work_order' => $v[3] ?: null,
                'risk_level' => $v[4] ?: null,
                'work_position' => $v[5] ?: null,
                'work_name' => $v[6] ?: null,
                'address' => $v[7] ?: null,
                'start_time' => $v[8] ?: null,
                'end_time' => $v[9] ?: null,
                'start_time_real' => $v[10] ?: null,
                'end_time_real' => $v[11] ?: null,
                'gk_measure' => $v[12] ?: null,
                'bc_measure' => $v[13] ?: null,
                'lc_status' => $v[14] ?: null,
                'oper_time' => date('Y-m-d H:i:s'),
            ];
        }

        (!empty($error_array)) && $this->error('上传异常：' . implode('，', $error_array));

        try {
            (new ProjectRiskModel())->insertAll($insert_array);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('上传成功');
    }
}
